<template>
  <button class="avatar-upload p-0 m-0 rounded" :style="styles" hover-class="none" open-type="chooseAvatar" @click="chooseAvatar" @chooseavatar="chooseAvatar">
    <image class="w-full h-full" mode="heightFix" :src="modelValue" v-if="modelValue" />
    <slot v-else>
      <div :style="styles" class="border border-dotted border-light flex w-full h-full flex-col items-center justify-center text-muted text-xs box-border rounded">
        <u-icon name="plus" :size="36" />
        添加图片
      </div>
    </slot>
  </button>
</template>
<script>
import { mapState } from 'vuex';
import { uploadFile } from '@/utils/util';
import { isBoolean } from 'lodash'
export default {
  props: {
    modelValue: {
      type: String
    },
    fileKey: {
      type: String,
      default: 'uri'
    },
    size: {
      type: String | Number,
      default: 120
    },
    round: {
      type: Boolean | String | Number,
      default: false
    },
    border: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    ...mapState(['temToken']),
    styles() {
      const size = uni.$u.addUnit(this.size);
      return {
        width: size,
        height: size,
        borderRadius: isBoolean(this.round) ? (this.round ? '50%' : '') : uni.$u.addUnit(this.round)
      };
    }
  },
  mounted() {
    uni.$on('uAvatarCropper', path => {
      this.uploadImageIng(path);
    });
  },
  unmounted() {
    uni.$off('uAvatarCropper');
  },
  methods: {
    chooseAvatar(e) {
      // #ifndef MP-WEIXIN
      uni.navigateTo({
        url: '/uni_modules/vk-uview-ui/components/u-avatar-cropper/u-avatar-cropper?destWidth=300&rectWidth=200&fileType=jpg'
      });
      // #endif
      // #ifdef MP-WEIXIN
      const path = e.detail.avatarUrl;
      if (path) {
        this.uploadImageIng(path);
      }
      // #endif
    },

    async uploadImageIng(file) {
      uni.showLoading({
        title: '正在上传中...'
      });
      try {
        const res = await uploadFile(file);
        uni.hideLoading();
        console.log(res);
        this.$emit('update:modelValue', res[this.fileKey]);
      } catch (error) {
        uni.hideLoading();
        uni.$u.toast(error);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.avatar-upload {
  background: #fff;
  overflow: hidden;
  &::after {
    border: none;
  }
}
</style>
